import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
var carlist = JSON.parse(localStorage.getItem('carlist') || [])
const store = new Vuex.Store({
    state: { //$store.state.***
        car: carlist,
    },
    mutations: {
        addIncar(state, goodInfo) {
            var filg = false;
            state.car.some(items => {
                if (items.id == goodInfo.id) {
                    items.content += parseInt(goodInfo.content);
                    filg = true;
                    return true;
                };
            })
            if (!filg) {
                state.car.push(goodInfo)
            }
            localStorage.setItem('carlist', JSON.stringify(state.car))
        },
        upcar(state, info) {
            state.car.forEach(items => {
                if (items.id == info.id) {
                    items.content = info.coent;
                    return true
                }

            })
        },
        removeCar(state, id) {
            state.car.some((items, i) => {
                if (items.id == id) {
                    state.car.splice(i, 1)
                    return true
                }

            })
            localStorage.setItem('carlist', JSON.stringify(state.car))
        },
        setchange(state, vae) {
            state.car.some(items => {
                if (items.id == vae.id) {
                    items.selected = vae.selected;
                    return true
                }

            })
            localStorage.setItem('carlist', JSON.stringify(state.car))
        }


    },
    getters: { //$store.getters.*****
        getAllNum(state) {
            var c = 0;
            state.car.forEach(ele => {
                c += parseInt(ele.content);
            });
            return c
        },
        getcarr(state) {
            var o = {};
            state.car.forEach(element => {
                o[element.id] = parseInt(element.content);
            });
            return o
        },
        getaddr(state) {
            var s = {};
            state.car.forEach(items => {
                s[items.id] = items.selected
            });
            return s

        },
        getout(state) {
            var a = {
                coent: 0,
                amiot: 0
            };
            state.car.forEach(items => {
                if (items.selected) {
                    a.coent += +items.content;
                    a.amiot += items.price * items.content;
                }
            })
            return a
        }

    }

});

export default store